<template>
  <div class="user-center-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="user-card">
          <div class="user-avatar">
            <el-avatar :size="100" :src="userInfo.avatar"></el-avatar>
          </div>
          <div class="user-name">{{ userInfo.username }}</div>
          <div class="join-time">加入时间：{{ formatDate(userInfo.createTime) }}</div>
          <el-menu
            :default-active="activeMenu"
            class="menu"
            @select="handleSelect"
          >
            <el-menu-item index="profile">
              <i class="el-icon-user"></i>
              <span slot="title">个人信息</span>
            </el-menu-item>
            <el-menu-item index="orders">
              <i class="el-icon-s-order"></i>
              <span slot="title">我的订单</span>
            </el-menu-item>
            <el-menu-item index="address">
              <i class="el-icon-location"></i>
              <span slot="title">收货地址</span>
            </el-menu-item>
            <el-menu-item index="security">
              <i class="el-icon-lock"></i>
              <span slot="title">账号安全</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <!-- 个人信息 -->
        <el-card v-if="activeMenu === 'profile'" class="content-card">
          <div slot="header">
            <span>个人信息</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="editMode = !editMode"
            >
              {{ editMode ? '取消' : '编辑' }}
            </el-button>
          </div>
          
          <el-form 
            :model="userForm" 
            :rules="rules" 
            ref="userForm" 
            label-width="80px"
            :disabled="!editMode"
          >
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader"
                action="/api/file/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :disabled="!editMode"
              >
                <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="userForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email"></el-input>
            </el-form-item>
            <el-form-item v-if="editMode">
              <el-button type="primary" @click="updateUserInfo">保存</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 我的订单 -->
        <el-card v-if="activeMenu === 'orders'" class="content-card">
          <div slot="header">
            <span>我的订单</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="$router.push('/order')"
            >
              查看全部
            </el-button>
          </div>
          
          <el-table
            :data="recentOrders"
            style="width: 100%"
            v-loading="ordersLoading"
          >
            <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
            <el-table-column prop="restaurantName" label="餐厅名称"></el-table-column>
            <el-table-column prop="payAmount" label="金额" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.payAmount }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" width="180">
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button size="mini" @click="viewOrderDetail(scope.row.id)">详情</el-button>
                <el-button 
                  v-if="scope.row.status === 0"
                  size="mini" 
                  type="danger" 
                  @click="cancelOrder(scope.row.id)"
                >
                  取消
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="recentOrders.length === 0 && !ordersLoading" class="empty-data">
            暂无订单数据
          </div>
        </el-card>
        
        <!-- 收货地址 -->
        <el-card v-if="activeMenu === 'address'" class="content-card">
          <div slot="header">
            <span>收货地址</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="showAddressDialog()"
            >
              添加新地址
            </el-button>
          </div>
          
          <div v-loading="addressesLoading">
            <el-empty v-if="addresses.length === 0" description="暂无收货地址"></el-empty>
            
            <el-card 
              v-for="address in addresses" 
              :key="address.id" 
              class="address-card" 
              :class="{ 'default-address': address.isDefault === 1 }"
              shadow="hover"
            >
              <div class="address-content">
                <div class="address-header">
                  <span class="receiver-info">{{ address.receiverName }} {{ address.receiverPhone }}</span>
                  <el-tag v-if="address.isDefault === 1" size="mini" type="success">默认地址</el-tag>
                </div>
                <div class="address-detail">
                  {{ address.province }} {{ address.city }} {{ address.district }} {{ address.detailAddress }}
                </div>
              </div>
              <div class="address-actions">
                <el-button type="text" size="small" @click="showAddressDialog(address)">编辑</el-button>
                <el-button type="text" size="small" @click="setDefaultAddress(address.id)" v-if="address.isDefault !== 1">设为默认</el-button>
                <el-button type="text" size="small" @click="deleteAddress(address.id)">删除</el-button>
              </div>
            </el-card>
          </div>
        </el-card>
        
        <!-- 账号安全 -->
        <el-card v-if="activeMenu === 'security'" class="content-card">
          <div slot="header">
            <span>账号安全</span>
          </div>
          
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input type="password" v-model="passwordForm.oldPassword" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input type="password" v-model="passwordForm.newPassword" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input type="password" v-model="passwordForm.confirmPassword" show-password></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="changingPassword">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 地址表单对话框 -->
    <el-dialog 
      :title="addressForm.id ? '编辑地址' : '添加地址'" 
      :visible.sync="addressDialogVisible"
      width="500px"
    >
      <el-form :model="addressForm" :rules="addressRules" ref="addressForm" label-width="100px">
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="addressForm.receiverName"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="receiverPhone">
          <el-input v-model="addressForm.receiverPhone"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" required>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="province">
                <el-select v-model="addressForm.province" placeholder="省份" style="width: 100%;">
                  <el-option label="北京市" value="北京市"></el-option>
                  <el-option label="上海市" value="上海市"></el-option>
                  <el-option label="广东省" value="广东省"></el-option>
                  <!-- 省份数据省略 -->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="city">
                <el-select v-model="addressForm.city" placeholder="城市" style="width: 100%;">
                  <el-option label="北京市" value="北京市"></el-option>
                  <el-option label="上海市" value="上海市"></el-option>
                  <el-option label="广州市" value="广州市"></el-option>
                  <!-- 城市数据省略 -->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="district">
                <el-select v-model="addressForm.district" placeholder="区县" style="width: 100%;">
                  <el-option label="朝阳区" value="朝阳区"></el-option>
                  <el-option label="海淀区" value="海淀区"></el-option>
                  <el-option label="天河区" value="天河区"></el-option>
                  <!-- 区县数据省略 -->
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailAddress">
          <el-input v-model="addressForm.detailAddress" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault" :true-label="1" :false-label="0">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addressDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAddress" :loading="savingAddress">确定</el-button>
      </div>
    </el-dialog>
    
    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="orderDialogVisible" width="60%">
      <div v-if="currentOrder" class="order-detail">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ currentOrder.orderNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span>{{ formatDate(currentOrder.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusType(currentOrder.status)" size="small">
              {{ getStatusText(currentOrder.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>配送信息</h4>
          <div class="detail-item">
            <span class="label">收货人：</span>
            <span>{{ currentOrder.receiverName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span>{{ currentOrder.receiverPhone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">配送地址：</span>
            <span>{{ currentOrder.receiverAddress }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>餐厅信息</h4>
          <div class="detail-item">
            <span class="label">餐厅名称：</span>
            <span>{{ currentOrder.restaurantName }}</span>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>商品信息</h4>
          <el-table :data="currentOrder.orderItems" border>
            <el-table-column prop="dishName" label="商品名称"></el-table-column>
            <el-table-column prop="dishPrice" label="单价" width="100">
              <template slot-scope="scope">¥{{ scope.row.dishPrice }}</template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
            <el-table-column label="小计" width="100">
              <template slot-scope="scope">¥{{ scope.row.dishPrice * scope.row.quantity }}</template>
            </el-table-column>
          </el-table>
          
          <div class="order-summary">
            <div class="summary-item">
              <span>商品总价：</span>
              <span>¥{{ currentOrder.totalAmount }}</span>
            </div>
            <div class="summary-item">
              <span>配送费：</span>
              <span>¥{{ currentOrder.deliveryFee }}</span>
            </div>
            <div class="summary-item total">
              <span>实付金额：</span>
              <span>¥{{ currentOrder.payAmount }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserCenter',
  data() {
    // 校验函数
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.passwordForm.confirmPassword !== '') {
          this.$refs.passwordForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (value && !/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    
    return {
      activeMenu: 'profile',
      userInfo: {},
      editMode: false,
      userForm: {
        username: '',
        realName: '',
        phone: '',
        email: '',
        avatar: ''
      },
      rules: {
        realName: [
          { max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ]
      },
      // 订单相关
      recentOrders: [],
      ordersLoading: false,
      orderDialogVisible: false,
      currentOrder: null,
      // 地址相关
      addresses: [],
      addressesLoading: false,
      addressDialogVisible: false,
      addressForm: {
        id: '',
        receiverName: '',
        receiverPhone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: 0
      },
      addressRules: {
        receiverName: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        receiverPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择城市', trigger: 'change' }
        ],
        district: [
          { required: true, message: '请选择区县', trigger: 'change' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      },
      savingAddress: false,
      // 密码相关
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      },
      changingPassword: false
    }
  },
  computed: {
    ...mapGetters(['isLoggedIn'])
  },
  created() {
    if (!this.isLoggedIn) {
      this.$router.push('/login')
      return
    }
    
    this.getUserInfo()
  },
  methods: {
    handleSelect(key) {
      this.activeMenu = key
      if (key === 'orders') {
        this.getRecentOrders()
      } else if (key === 'address') {
        this.getAddresses()
      }
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    getUserInfo() {
      this.$http.get('/user/info')
        .then(response => {
          this.userInfo = response.data.data
          // 复制用户信息到表单
          this.userForm = { ...this.userInfo }
        })
        .catch(error => {
          this.$message.error('获取用户信息失败')
          console.error('获取用户信息失败', error)
        })
    },
    updateUserInfo() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.$http.put('/user/info', this.userForm)
            .then(() => {
              this.$message.success('个人信息更新成功')
              this.editMode = false
              this.getUserInfo() // 重新获取用户信息
            })
            .catch(error => {
              this.$message.error((error.response && error.response.data && error.response.data.message) || '更新失败')
            })
        }
      })
    },
    resetForm() {
      this.$refs.userForm.resetFields()
      this.userForm = { ...this.userInfo }
    },
    handleAvatarSuccess(res, file) {
      this.userForm.avatar = URL.createObjectURL(file.raw)
      // 实际项目中应该上传到服务器并获取URL
      // this.userForm.avatar = res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 订单相关方法
    getRecentOrders() {
      this.ordersLoading = true
      this.$http.get('/order/list', {
        params: {
          page: 1,
          size: 5
        }
      })
        .then(response => {
          const { data } = response.data
          this.recentOrders = data.records
        })
        .catch(error => {
          this.$message.error('获取订单列表失败')
          console.error('获取订单列表失败', error)
        })
        .finally(() => {
          this.ordersLoading = false
        })
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'success',
        4: 'info'
      }
      return typeMap[status] || 'info'
    },
    viewOrderDetail(orderId) {
      this.$http.get(`/order/${orderId}`)
        .then(response => {
          this.currentOrder = response.data.data
          this.orderDialogVisible = true
        })
        .catch(error => {
          this.$message.error('获取订单详情失败')
          console.error('获取订单详情失败', error)
        })
    },
    cancelOrder(orderId) {
      this.$confirm('确认取消该订单吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.put(`/order/${orderId}/cancel`)
          .then(() => {
            this.$message.success('订单已取消')
            this.getRecentOrders()
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '取消订单失败')
          })
      }).catch(() => {})
    },
    // 地址相关方法
    getAddresses() {
      this.addressesLoading = true
      this.$http.get('/user/address')
        .then(response => {
          this.addresses = response.data.data
        })
        .catch(error => {
          this.$message.error('获取收货地址失败')
          console.error('获取收货地址失败', error)
        })
        .finally(() => {
          this.addressesLoading = false
        })
    },
    showAddressDialog(address) {
      if (address) {
        this.addressForm = { ...address }
      } else {
        this.addressForm = {
          id: '',
          receiverName: '',
          receiverPhone: '',
          province: '',
          city: '',
          district: '',
          detailAddress: '',
          isDefault: 0
        }
      }
      this.addressDialogVisible = true
    },
    saveAddress() {
      this.$refs.addressForm.validate(valid => {
        if (valid) {
          this.savingAddress = true
          
          const savePromise = this.addressForm.id
            ? this.$http.put(`/user/address/${this.addressForm.id}`, this.addressForm)
            : this.$http.post('/user/address', this.addressForm)
            
          savePromise
            .then(() => {
              this.$message.success(this.addressForm.id ? '地址修改成功' : '地址添加成功')
              this.addressDialogVisible = false
              this.getAddresses()
            })
            .catch(error => {
              this.$message.error((error.response && error.response.data && error.response.data.message) || (this.addressForm.id ? '修改失败' : '添加失败'))
            })
            .finally(() => {
              this.savingAddress = false
            })
        }
      })
    },
    setDefaultAddress(id) {
      const address = this.addresses.find(a => a.id === id)
      if (address) {
        address.isDefault = 1
        this.$http.put(`/user/address/${id}`, { isDefault: 1 })
          .then(() => {
            this.$message.success('已设为默认地址')
            this.getAddresses()
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '设置默认地址失败')
          })
      }
    },
    deleteAddress(id) {
      this.$confirm('确认删除该地址吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/user/address/${id}`)
          .then(() => {
            this.$message.success('地址已删除')
            this.getAddresses()
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '删除地址失败')
          })
      }).catch(() => {})
    },
    // 密码相关方法
    changePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.changingPassword = true
          // 实际项目中应该调用修改密码API
          setTimeout(() => {
            this.$message.success('密码修改成功')
            this.resetPasswordForm()
            this.changingPassword = false
          }, 1000)
        }
      })
    },
    resetPasswordForm() {
      this.$refs.passwordForm.resetFields()
    }
  }
}
</script>

<style scoped>
.user-center-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.user-card {
  padding: 20px;
  text-align: center;
  margin-bottom: 20px;
  height: 100%;
}

.user-avatar {
  margin-bottom: 15px;
}

.user-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.join-time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 20px;
}

.menu {
  border-right: none;
  margin-top: 20px;
}

.content-card {
  min-height: 400px;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.empty-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}

/* 地址样式 */
.address-card {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.default-address {
  border: 1px solid #67C23A;
}

.address-content {
  flex: 1;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.receiver-info {
  font-weight: bold;
  margin-right: 10px;
}

.address-detail {
  color: #606266;
  font-size: 14px;
}

.address-actions {
  display: flex;
  flex-direction: column;
}

/* 订单详情样式 */
.order-detail {
  padding: 0 20px;
}

.detail-section {
  margin-bottom: 30px;
}

.detail-section h4 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.detail-item {
  display: flex;
  margin-bottom: 10px;
}

.detail-item .label {
  width: 100px;
  color: #909399;
}

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.summary-item {
  margin-bottom: 10px;
}

.summary-item.total {
  font-weight: bold;
  color: #f56c6c;
  font-size: 16px;
}
</style>
